package com.wenhai.leetcode.linkedList;

/**
 * https://leetcode-cn.com/problems/remove-linked-list-elements/
 *
 * @ClassName _203移除链表元素
 * @Description
 * @Author 谢文海
 * @Date 2021/2/21 18:54
 * @Version 1.0
 **/
public class _203移除链表元素 {

    public static ListNode removeElements(ListNode head, int val) {
        while (head != null && head.val == val) {
            ListNode delNode = head;
            head = head.next;
            delNode.next = null;
        }
        if (head == null) {
            return null;
        }

        ListNode prev = head;

        while (prev.next != null) {
            if (prev.next.val == val) {
                ListNode delNode = prev.next;
                prev.next = delNode.next;
                delNode.next = null;
            } else {
                prev = prev.next;
            }

        }
        return head;
    }
    public static ListNode removeElements2(ListNode head, int val) {
        ListNode dummyHead = new ListNode(val + 1, head);
        ListNode prev = dummyHead;
        while (prev.next != null) {
            if (prev.next.val == val) {
                ListNode delNode = prev.next;
                prev.next = delNode.next;
                delNode.next = null;
            } else {
                prev = prev.next;
            }

        }
        return dummyHead.next;
    }

    public static ListNode removeElements3(ListNode head, int val) {
        if (head == null) {
            return head;
        }
        head.next = removeElements3(head.next, val);
        return head.val == val ? head.next : head;
    }

    public static class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }


}
